<template>
  <div class="setting">
    <h2>动作管理</h2>
    <el-button type="primary" size="mini" @click="addAction">添加动作</el-button>

    <div class="consultation-block">
      <div class="table">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="名称"> </el-table-column>
          <el-table-column prop="type" label="分类"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                @click="updateAction(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteAction(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="refreshTable"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="添加动作"
      :visible.sync="isVisible"
      :close-on-click-modal="false"
      width="70%"
      :before-close="handleAddClose"
    >
      <el-form
        :model="addForm"
        status-icon
        :rules="rules2"
        size="mini"
        ref="addForm"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input :min="0" type="text" v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            :action="'/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
          >
            <i
              v-if="!addForm.cover"
              class="el-icon-plus avatar-uploader-icon"
            ></i>
            <img
              v-if="addForm.cover"
              :src="addForm.cover"
              style="width: 80px"
            />
          </el-upload>
        </el-form-item>
        <el-form-item label="商品详情">
          <vue-editor
            v-model="addForm.content"
            useCustomImageHandler
            @image-added="handleImageAdded"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAction,
  addAction,
  updateAction,
  deleteAction,
  getType
} from "../service.js";
import moment from "moment";
import { VueEditor } from "vue2-editor";

export default {
  components: { VueEditor },
  data() {
    return {
      tableData: [],
      isVisible: false,
      rules2: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        type: [{ required: true, message: "请输入", trigger: "blur" }],
        cover: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      typeList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      addForm: {},
    };
  },
  mounted() {
    this.refreshTable();
    getType({
      page: 1,
      pageSize: 1111,
    }).then((res) => {
      this.typeList = res.data.data
        .filter((v) => v.parentId)
        .map((v) => v.name);
    });
  },
  methods: {
    handleAddClose() {
      this.isVisible = false;
    },
    addAction() {
      this.addForm = {
        name: "",
        content: "",
        cover: "",
        type: "",
      };
      this.isVisible = true;
    },
    handleAvatarSuccess2(info) {
      console.log("handleAvatarSuccess2", info);
      this.addForm.cover = info.imgName;
    },
    refreshTable() {
      getAction({
        page: this.currentPage,
        pageSize: this.pageSize,
      }).then((res) => {
        this.tableData = res.data.data;
        this.total = res.data.total;
      });
    },
    deleteImg(index) {
      this.addForm.imgs.splice(index, 1);
    },
    updateAction(row) {
      this.addForm = JSON.parse(JSON.stringify(row));
      this.isVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addForm.id) {
            updateAction(this.addForm.id, this.addForm).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.isVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg);
              }
            });
            // 编辑
          } else {
            addAction({
              ...this.addForm,
              updateTime: new Date(),
            }).then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.isVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    },
    deleteAction(row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteAction(row.id).then((res) => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.isVisible = false;
            this.refreshTable();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 处理富文本编辑框的图片
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      var xhr = new XMLHttpRequest();
      xhr.open("post", "http://localhost:3000/upload");
      xhr.send(formData);
      xhr.onload = function () {
        if (xhr.status == 200) {
          console.log(xhr.responseText);
          let res = JSON.parse(xhr.responseText);
          const url = "http://localhost:3000/" + res.imgName;
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        }
      };
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
</style>
